#!/bin/bash
# 备份脚本

BACKUP_DIR="/opt/backups/erp-mock"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
SOURCE_DIR="/opt/erp-mock"
RETENTION_DAYS=30

echo "========================================"
echo "ERP Mock Server 备份脚本"
echo "开始时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo "========================================"

# 创建备份目录
mkdir -p $BACKUP_DIR

# 打包备份（排除虚拟环境、日志和缓存）
echo "正在备份应用..."
tar -czf $BACKUP_DIR/erp-mock-$TIMESTAMP.tar.gz \
    --exclude='venv' \
    --exclude='logs/*.log' \
    --exclude='logs/*.log.*' \
    --exclude='__pycache__' \
    --exclude='*.pyc' \
    --exclude='.git' \
    -C /opt erp-mock

if [ $? -eq 0 ]; then
    BACKUP_SIZE=$(du -h $BACKUP_DIR/erp-mock-$TIMESTAMP.tar.gz | cut -f1)
    echo "✓ 备份完成: erp-mock-$TIMESTAMP.tar.gz ($BACKUP_SIZE)"
else
    echo "✗ 备份失败"
    exit 1
fi

# 删除过期备份
echo "正在清理过期备份（保留${RETENTION_DAYS}天）..."
DELETED_COUNT=$(find $BACKUP_DIR -name "erp-mock-*.tar.gz" -type f -mtime +$RETENTION_DAYS -delete -print | wc -l)
echo "✓ 已删除 $DELETED_COUNT 个过期备份"

# 显示当前备份列表
echo ""
echo "当前备份列表："
ls -lh $BACKUP_DIR | tail -n 5

echo ""
echo "备份完成时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo "========================================"
